package com.jgc.blockingqueue;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * LinkedBlockingQueue是基于链表实现的，和ArrayBlockingQueue不同的是，
 * 大小可以初始化设置，如果不设置，默认设置大小为Integer.MAX_VALUE，LinkedBlockingQueue有两个锁对象，可以并行处理
 */
public class LinkedBlockingQueueTest {
    // 创建一个无界（默认最大容量为Integer.MAX_VALUE）的任务队列
    private final static LinkedBlockingQueue<String> taskQueue = new LinkedBlockingQueue<>();
    public static class Producer implements Runnable {
        @Override
        public void run() {
            String[] tasks = {"Task A", "Task B", "Task C", "Task D", "Task E", "Task F"};

            for (String task : tasks) {
                try {
                    // 将任务放入队列，如果队列满（但这里是无界队列，所以一般不会发生这种情况），则阻塞等待
                    taskQueue.put(task);
                    System.out.println("Producer put task: " + task);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("Producer interrupted while trying to put task");
                    return;
                }
            }
            System.out.println("All tasks have been produced. Stopping the producer.");
        }
    }

    public static class Consumer implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 从队列取出一个任务，如果队列为空，则阻塞等待
                    String task = taskQueue.poll(5, TimeUnit.SECONDS); // 等待最多5秒，如果没有任务则继续等待下一轮
                    if (task != null) {
                        System.out.println("Consumer took task: " + task + ", processing...");
                        // 处理任务的代码...
                    } else {
                        System.out.println("No task available within 5 seconds, continuing to wait...");
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("Consumer interrupted while trying to take task");
                    return;
                }
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread producerThread = new Thread(new Producer());
        Thread consumerThread = new Thread(new Consumer());

        producerThread.start();
        consumerThread.start();

        // 确保生产者完成任务后程序才结束
        producerThread.join();

        // 在实际应用中，可能需要某种机制来停止消费者线程
        // 这里为了演示，我们简单地让主程序等待一段时间后退出，消费者线程可能会因为 JVM 停止而终止
        TimeUnit.SECONDS.sleep(10);
    }
}

